<template>
	<div class="app-container">
		<el-row :gutter="20">
			<el-col :span="3" :xs="24">
				<div class="head-container">
					<el-input v-model="categoryTitle" placeholder="请输入栏目名称" clearable size="small" prefix-icon="el-icon-search" style="margin-bottom: 20px"/>
				</div>
				<div class="head-container">
					<el-tree
						:data="categoryOptions2"
						:props="defaultProps"
						:expand-on-click-node="false"
						:filter-node-method="filterNode"
						ref="tree"
						node-key="id"
						default-expand-all
						highlight-current
						@node-click="handleNodeClick"
					/>
				</div>
			</el-col>
			<el-col :span="20" :xs="24" v-if="categoryType == 1 && !checkPermi(['admin'])">
				<content-form :form="form" :categoryOptions="categoryOptions1" :isInsert="isInsert" :isEdit="isEdit" @submitForm="submitForm" @cancel="cancel" :disabledCategory="true"/>
			</el-col>
			<el-col :span="20" :xs="24" v-else>
				<el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px" @submit.native.prevent>
					<el-form-item label="文章标题" prop="contentTitle">
						<el-input v-model="queryParams.contentTitle" placeholder="请输入" clearable @keyup.enter="handleQuery"/>
					</el-form-item>
					<el-form-item label="关键字" prop="contentKeyword">
						<el-input v-model="queryParams.contentKeyword" placeholder="请输入" clearable @keyup.enter="handleQuery"/>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
						<el-button icon="Refresh" @click="resetQuery">重置</el-button>
					</el-form-item>
				</el-form>

				<el-row :gutter="10" class="mb8">
					<el-col :span="1.5">
						<el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['cm:cmContent:add']">新增</el-button>
					</el-col>
					<el-col :span="1.5">
						<el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate" v-hasPermi="['cm:cmContent:edit']">修改</el-button>
					</el-col>
					<el-col :span="1.5">
						<el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['cm:cmContent:remove']">删除</el-button>
					</el-col>
					<el-col :span="1.5">
						<el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['cm:cmContent:export']">导出</el-button>
					</el-col>
					<right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
				</el-row>

				<el-table v-loading="loading" :data="cmContentList" @selection-change="handleSelectionChange">
					<el-table-column type="selection" width="55" align="center"/>
					<el-table-column label="所属栏目" align="center" prop="categoryId" v-if="columnVisible('categoryId')">
						<template #default="scope">
							{{ categoryOptionsMap[scope.row.categoryId] ? categoryOptionsMap[scope.row.categoryId].categoryTitle : '' }}
						</template>
					</el-table-column>
					<el-table-column label="文章标题" align="center" prop="contentTitle" v-if="columnVisible('contentTitle')"/>
					<el-table-column label="缩略图" align="center" prop="contentImg" width="100" v-if="columnVisible('contentImg')">
						<template #default="scope">
							<image-preview :src="scope.row.contentImg" :width="50" :height="50"/>
						</template>
					</el-table-column>
					<el-table-column label="关键字" align="center" prop="contentKeyword" v-if="columnVisible('contentKeyword')"/>
					<el-table-column label="文章内容" align="center" prop="contentDetails" v-if="columnVisible('contentDetails')"/>
					<el-table-column label="文章描述" align="center" prop="contentDescription" v-if="columnVisible('contentDescription')"/>
					<el-table-column label="点击次数" align="center" prop="contentHit" v-if="columnVisible('contentHit')"/>
					<el-table-column label="虚拟点击次数" align="center" prop="contentHitVirtual" v-if="columnVisible('contentHitVirtual')"/>
					<el-table-column label="文章作者" align="center" prop="contentAuthor" v-if="columnVisible('contentAuthor')"/>
					<el-table-column label="排序" align="center" prop="sort" v-if="columnVisible('sort')"/>
					<el-table-column label="是否推荐" align="center" prop="isRecommend" v-if="columnVisible('isRecommend')">
						<template #default="scope">
							<dict-tag :options="sys_yes_no" :value="scope.row.isRecommend"/>
						</template>
					</el-table-column>
					<el-table-column label="状态" align="center" prop="status" v-if="columnVisible('status')">
						<template #default="scope">
							<el-switch v-model="scope.row.status" :active-value="0" :inactive-value="1" @change="handleStatusChange(scope.row,'status')"></el-switch>
						</template>
					</el-table-column>
					<el-table-column label="归属部门" align="center" prop="deptId" v-if="columnVisible('deptId')">
						<template #default="scope">
							<span>{{ deptName(scope.row.deptId) }}</span>
						</template>
					</el-table-column>
					<el-table-column label="备注" align="center" prop="remark" v-if="columnVisible('remark')"/>
					<el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
						<template #default="scope">
							<el-button link type="primary" icon="View" @click="handleView(scope.row)" v-hasPermi="['cm:cmContent:query']" v-noPermi="['cm:cmContent:edit']">查看</el-button>
							<el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['cm:cmContent:edit']">修改</el-button>
							<el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['cm:cmContent:remove']">删除</el-button>
						</template>
					</el-table-column>
				</el-table>

				<pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList"/>
			</el-col>
		</el-row>
		<!-- 添加或修改文章管理对话框 -->
		<el-dialog :title="title" v-model="open" width="1200" append-to-body>
			<content-form v-if="open" :form="form" :categoryOptions="categoryOptions1" :isInsert="isInsert" :isEdit="isEdit" @submitForm="submitForm" @cancel="cancel"/>
		</el-dialog>
	</div>
</template>

<script setup name="CmContent">
import {listCmContent, getCmContent, delCmContent, addCmContent, updateCmContent} from "@/api/cm/cmContent";
import {checkPermi} from "@/utils/permission.js";
import ContentForm from "@/views/cm/cmContent/form.vue";

const {proxy} = getCurrentInstance();
const {sys_data_status, sys_yes_no} = proxy.useDict('sys_data_status', 'sys_yes_no');

import useUserStore from "@/store/modules/user";

const userStore = useUserStore();

const cmContentList = ref([]);
const isEdit = ref(false);
const isInsert = ref(false);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
// 列显隐信息(able表示列是否可用，visible用于用户控制显隐)
const columns = ref([
	{label: `id`, able: false, visible: false, key: 'id'},
	{label: `所属栏目`, able: true, visible: true, key: 'categoryId'},
	{label: `文章标题`, able: true, visible: true, key: 'contentTitle'},
	{label: `缩略图`, able: true, visible: true, key: 'contentImg'},
	{label: `关键字`, able: true, visible: true, key: 'contentKeyword'},
	{label: `文章内容`, able: false, visible: true, key: 'contentDetails'},
	{label: `文章描述`, able: false, visible: true, key: 'contentDescription'},
	{label: `点击次数`, able: true, visible: true, key: 'contentHit'},
	{label: `虚拟点击次数`, able: false, visible: true, key: 'contentHitVirtual'},
	{label: `文章作者`, able: true, visible: true, key: 'contentAuthor'},
	{label: `纬度`, able: false, visible: true, key: 'lat'},
	{label: `经度`, able: false, visible: true, key: 'lng'},
	{label: `排序`, able: false, visible: true, key: 'sort'},
	{label: `是否推荐`, able: true, visible: true, key: 'isRecommend'},
	{label: `删除标志`, able: false, visible: false, key: 'delFlag'},
	{label: `状态`, able: true, visible: true, key: 'status'},
	{label: `归属部门`, able: true, visible: true, key: 'deptId'},
	{label: `创建者`, able: false, visible: false, key: 'createBy'},
	{label: `创建时间`, able: false, visible: false, key: 'createTime'},
	{label: `更新者`, able: false, visible: false, key: 'updateBy'},
	{label: `更新时间`, able: false, visible: false, key: 'updateTime'},
	{label: `备注`, able: true, visible: true, key: 'remark'},
]);

const data = reactive({
	form: {},
	queryParams: {
		pageNum: 1,
		pageSize: 10,
		params: {},
		categoryId: null,
		contentTitle: null,
		contentKeyword: null,
		contentHit: null,
		contentHitVirtual: null,
		contentAuthor: null,
		lat: null,
		lng: null,
		sort: null,
		isRecommend: null,
		status: null,
		deptId: null,
	},
	rules: {
		categoryId: [{required: true, message: "所属栏目不能为空", trigger: "blur"}],
		contentTitle: [{required: true, message: "文章标题不能为空", trigger: "blur"}],
		sort: [{required: true, message: "排序不能为空", trigger: "blur"}],
	}
});

const {queryParams, form, rules} = toRefs(data);

/** 列显隐 */
function columnVisible(key) {
	return proxy.checkColumn(columns.value, key);
}

/** 查询文章管理列表 */
function getList() {
	loading.value = true;
	listCmContent(queryParams.value).then(response => {
		cmContentList.value = response.rows;
		total.value = response.total;
		loading.value = false;
		if (categoryType.value && categoryType.value == 1) {
			if (response.rows && response.rows.length) {
				form.value = response.rows[0] || {}
				isEdit.value = true;
			} else {
				reset();
				isInsert.value = true;
			}
		}
	});
}

// 取消按钮
function cancel() {
	open.value = false;
	reset();
}

// 表单重置
function reset() {
	form.value = {
		id: null,
		categoryId: categoryId.value,
		contentTitle: null,
		contentImg: null,
		contentKeyword: null,
		contentDetails: null,
		contentDescription: null,
		contentHit: null,
		contentHitVirtual: null,
		contentAuthor: null,
		lat: null,
		lng: null,
		sort: null,
		isRecommend: 0,
		delFlag: null,
		status: 0,
		deptId: userStore.deptId,
		createBy: null,
		createTime: null,
		updateBy: null,
		updateTime: null,
		remark: null
	};
}

/** 搜索按钮操作 */
function handleQuery() {
	queryParams.value.pageNum = 1;
	getList();
}

/** 重置按钮操作 */
function resetQuery() {
	proxy.resetForm("queryRef");
	handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
	ids.value = selection.map(item => item.id);
	single.value = selection.length != 1;
	multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
	reset();
	open.value = true;
	title.value = "添加文章管理";
	isInsert.value = true;
	isEdit.value = false;
}

/** 查看按钮操作 */
function handleView(row) {
	isEdit.value = false;
	title.value = "查看文章管理";
	getInfo(row);
}

/** 修改按钮操作 */
function handleUpdate(row) {
	isEdit.value = true;
	title.value = "修改文章管理";
	getInfo(row);
}

function getInfo(row) {
	reset();
	const _id = row.id || ids.value
	isInsert.value = false;
	proxy.modal.loading("加载中");
	getCmContent(_id).then(response => {
		form.value = response.data;
		open.value = true;
		proxy.modal.closeLoading();
	}).catch(err => {
		Promise.reject(err);
		proxy.modal.closeLoading();
	});
}

/** 提交按钮 */
function submitForm() {
	if (form.value.id != null) {
		proxy.modal.loading("提交中");
		updateCmContent(form.value).then(response => {
			proxy.modal.msgSuccess("修改成功");
			open.value = false;
			getList();
			proxy.modal.closeLoading();
		}).catch(err => {
			proxy.modal.closeLoading();
			Promise.reject(err);
		});
	} else {
		proxy.modal.loading("提交中");
		addCmContent(form.value).then(response => {
			proxy.modal.msgSuccess("新增成功");
			open.value = false;
			getList();
			proxy.modal.closeLoading();
		}).catch(err => {
			proxy.modal.closeLoading();
			Promise.reject(err);
		});
	}
}

/** 删除按钮操作 */
function handleDelete(row) {
	const _ids = row.id || ids.value;
	proxy.modal.confirm('是否确认删除文章管理编号为"' + _ids + '"的数据项？').then(function () {
		proxy.modal.loading("删除中");
		return delCmContent(_ids);
	}).then(() => {
		getList();
		proxy.modal.msgSuccess("删除成功");
		proxy.modal.closeLoading();
	}).catch(() => {
		proxy.modal.closeLoading();
	});
}

/** 导出按钮操作 */
function handleExport() {
	proxy.download.post('cm/cmContent/export', {
		...queryParams.value
	}, `cmContent_${new Date().getTime()}.xlsx`)
}

/** 状态修改  */
function handleStatusChange(row, key) {
	let text = row[key] ? "停用" : "启用";
	proxy.modal.confirm('确认要【' + text + '】"' + row.id + '"数据项吗?').then(function () {
		return updateCmContent({id: row.id, [key]: row[key]});
	}).then(() => {
		proxy.modal.msgSuccess(text + "成功");
	}).catch(function () {
		row[key] = row[key] ? 0 : 1;
	});
};

import {listCmCategory} from "@/api/cm/cmCategory.js";

/** 栏目类型 */
const categoryId = ref(null);
const categoryType = ref(null);
const categoryTitle = ref(null);
const categoryOptionsMap = ref({});
const categoryOptions1 = ref([]);
const categoryOptions2 = ref([]);
const defaultProps = ref({
	id: "id",
	label: "categoryTitle",
	children: "children",
})

// 筛选节点
function filterNode(value, data) {
	if (!value) return true;
	return data.categoryTitle.indexOf(value) !== -1 || !data.id;
}

// 节点单击事件
function handleNodeClick(data) {
	queryParams.value.categoryId = data.id;
	categoryId.value = data.id;
	categoryType.value = data.categoryType;
	reset();
	handleQuery(categoryType.value, true);
}

listCmCategory().then(response => {
	//树形选择
	let children = proxy.handleTree(response.data, "id", "parentId")
	if (!checkPermi(['admin'])) {
		children = children.filter(item => !item.isAdmin)
	}
	categoryOptions1.value = [{id: '', categoryTitle: "顶级栏目", children: children, disabled: true}];
	categoryOptions2.value = [{id: null, categoryTitle: "全部栏目", children: children, disabled: true}];
	categoryOptionsMap.value = {};
	response.data.forEach(item => {
		categoryOptionsMap.value[item.id] = item
	})
});


getList();
</script>
